import logger from "./logger";
import gamedata, { farmerconfig } from "./gamedata";
import netMgr, { Apis } from "./netMgr";
import GameConfig from "../GameConfig";
import homescript from "../scripts/homescript";
// wxde0a7200c55e251b   appid
export default class wxutils {
    public userInfo;
    private static _Instance: wxutils;
    public SystemInfo;
    public boxMain: { y: number, width: number, height: number }
    public static get Instance(): wxutils {
        if (!this._Instance)
            this._Instance = new wxutils();
        return this._Instance;
    }
    constructor() {

    }
    //登陆
    lgoin() {
        if (typeof wx === 'undefined') {
            return
        }
        //@ts-ignore
        wx.login({//获取code 换取openid
            success: (res) => {
                console.log("请求login")
                logger.log("code:", res);
                netMgr.Instance.post(netMgr.Instance.baseUrl + Apis.Login, { appName: 'mibao', code: res.code }, (res) => {
                    logger.log("微信登陆请求--->", res)
                    if (res.code == 200 || res.code == 0 || res.msg == "success") {//请求成功 赋值openid
                        gamedata.Instance.openid = res.data;
                        wxutils.Instance.init(() => {
                            this.getSystemInfo();
                        });
                    } else {//请求失败处理位置
                        logger.log("获取登陆信息失败");
                    }
                })
            }
        })
    }

    //获取用户信息老陈  //获取到级别  用户道具信息等============执行对应回调
    getUserInfoChen() {
        netMgr.Instance.get(netMgr.Instance.baseUrl + Apis.UserInfo, (res) => {
            gamedata.Instance.userData = res;
            this.initHearBeat();
            logger.log("开始执行逻辑代码--->");
            // 加载IDE指定的场景//---------------------------------打开页面执行逻辑部分代码---------------------------------------------
            GameConfig.startScene && Laya.Scene.open(GameConfig.startScene);
            console.log("配置数据：", gamedata.Instance.peizhi);
            console.log("用户数据：", gamedata.Instance.userData);
            // for(let j in gamedata.Instance.userData.data.products){
            //     for(let i in gamedata.Instance.peizhi.product_conf){
            //         console.log(gamedata.Instance.peizhi.product_conf[i])
            //         if(gamedata.Instance.peizhi.product_conf[i].id.toString()==gamedata.Instance.userData.data.products[j].id.toString()){
            //             console.log(gamedata.Instance.peizhi.product_conf[i],gamedata.Instance.userData.data.products[j])
            //         }
            //     }
            // }
        })
    }

    //初始化 获取用户基本信息
    init(method: any) {
        if (typeof wx === 'undefined') {
            return;
        }
        wx.getSetting({//获取用户当前设置
            success: (res) => {
                logger.log("-----getsetting----->", res);
                //@ts-ignore
                if (res.authSetting['scope.userInfo']) {
                    this.getUserInfo(method)
                } else {
                    logger.log("开始请求权限");
                    wx.authorize({//提前向用户发起授权请求。调用后会立刻弹窗询问用户是否同意授权小程序使用某项功能或获取用户的某些数据，但不会实际调用对应接口。如果用户之前已经同意授权，则不会出现弹窗，直接返回成功
                        scope: 'scope.userInfo', success: (res) => {
                            console.log('权限请求结果', res)
                            this.getUserInfo(method)
                        }, fail: () => { }, complete: () => { }
                    })
                }
            }, fail: () => { }, complete: () => { }
        })
    }

    getUserInfo(method) {//获取用户信息，withCredentials 为 true 时需要先调用 wx.login 接口。
        wx.getUserInfo({
            success: (res) => {
                // logger.log("用户数据：", res)
                this.userInfo = res;
                this.setUserData(res);
                this.getInfoCallBack(method);//================================================微信登陆执行完毕

                // 此处可以获取到用户信息
            }, fail: () => { }, complete: () => { }, lang: 'zh_CN', withCredentials: true
        })
    }

    //获取用户数据的回调函数
    getInfoCallBack(method) {
        let hd = new Laya.Handler(this, method);
        hd.run();
    }

    //存储数据
    setUserData(data) {
        logger.log("data:", data)
        gamedata.Instance.userInfo = data.userInfo;
        gamedata.Instance.encryptedData = data.encryptedData;
        gamedata.Instance.errMsg = data.errMsg;
        gamedata.Instance.iv = data.iv;
        gamedata.Instance.signature = data.signature;
    }


    //获取手机信息
    public getSystemInfo() {
        //@ts-ignore
        wx.getSystemInfo({
            success: (info) => {
                console.log("系统信息：", info);
                this.SystemInfo = info;
                console.log("状态栏高度：", info.statusBarHeight);
                this.getPeiZhi();
                this.initBoxMain();
            }
        })

    }

    //心跳
    public initHearBeat() {
        Laya.timer.loop(farmerconfig.hearBeatTime, this, () => {
            netMgr.Instance.get(netMgr.Instance.baseUrl + Apis.Heartbeat, (res) => {
                logger.log("heartBeat-->", res)
            })
        })
    }


    //配置信息
    public getPeiZhi() {
        console.log("请求配置")
        netMgr.Instance.get(netMgr.Instance.baseUrl + Apis.PeiZhi, (res) => {
            logger.log("请求配置", res);
            gamedata.Instance.peizhi = res;
            this.getUserInfoChen();//从老陈那里获取数据

        })


        // // 无配置 暂时测试用
        // // logger.log("请求配置", res);
        // // gamedata.Instance.peizhi = res;
        // this.getUserInfoChen();//从老陈那里获取数据
    }

    //初始化boxmain的属性
    public initBoxMain() {
        let shejiwidth = 720;
        let shejiheight = 1560;
        let realHeight = 720 * innerHeight / innerWidth;
        let height = this.SystemInfo.statusBarHeight;
        let winheight = this.SystemInfo.windowHeight;
        let y = realHeight * height / winheight;
        this.boxMain = { width: 720, height: realHeight - y, y: y }
        logger.log("boxmain:", this.boxMain);
    }


    //分享
    public fenxiang() {
        // wx.getFriendCloudStorage({success:(res)=>{console.log("获取成功",res)}})
        //@ts-ignore
        console.log("分享", wx.setMessageToFriendQuery)
        //@ts-ignore
        wx.setMessageToFriendQuery({openId:gamedata.Instance.openid,title:"转发测试",imageUrl:"www.img.img",imageUrlId:'www.baidu.img'  })
    }

}




//微信步数=========================================
// Laya.stage.on(Laya.Event.DOUBLE_CLICK, this, () => {
//     wx.getWeRunData({
//         success: (res) => {
//             // 拿 encryptedData 到开发者后台解密开放数据
//             const encryptedData = res.encryptedData
//             // 或拿 cloudID 通过云调用直接获取开放数据
//             // const cloudID = res.cloudID
//             console.log("微信运动数据-->", res)
//         }, fail: () => {

//         }, complete: () => {

//         }
//     })
// })